package com.ksd.pug.config.interceptor.sms;


import com.ksd.pug.commons.ex.PugValidationException;
import com.ksd.pug.commons.utils.ip.IpUtils;
import com.ksd.pug.utils.redis.PugRedisOperator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 短信重复发送拦截
 * @date 2022/3/6$ 2:51$
 */
@Component
@Slf4j
public class SmsInterceptor implements HandlerInterceptor{

    @Autowired
    private PugRedisOperator redisOperator;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取用户ip
        log.info("短信发送验证");
        String userIp = IpUtils.getIpAddr(request);
        boolean isExist = redisOperator.keyIsExist("xq:login:sms:limit:" + userIp);
        if (isExist) {
            log.info("短信发布频率太大");
            throw new PugValidationException(601, "短信发布频率太大");
        }
        log.info("短信发送验证通过");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
